package com.sjy.project.fym.team.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.validation.Validator;

import com.sjy.common.exception.ServiceException;
import com.sjy.common.utils.DateUtils;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.bean.BeanValidators;
import com.sjy.common.utils.security.ShiroUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sjy.project.fym.team.mapper.FyTeamMapper;
import com.sjy.project.fym.place.domain.FyPlace;
import com.sjy.project.fym.place.mapper.FyPlaceMapper;
import com.sjy.project.fym.team.domain.FyTeam;
import com.sjy.project.fym.team.service.IFyTeamService;
import com.sjy.project.fym.user.mapper.FyUserMapper;
import com.sjy.project.system.user.service.UserServiceImpl;
import com.sjy.common.utils.text.Convert;
import com.sjy.framework.web.domain.Ztree;

/**
 * 防疫队伍Service业务层处理
 * 
 * @author sjy
 * @date 2022-04-18
 */
@Service
public class FyTeamServiceImpl implements IFyTeamService 
{
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private FyTeamMapper fyTeamMapper;
    @Autowired
    private FyUserMapper fyUserMapper;
    @Autowired
    private FyPlaceMapper fyPlaceMapper;
    @Autowired
    protected Validator validator;

    /**
     * 查询防疫队伍
     * 
     * @param teamId 防疫队伍主键
     * @return 防疫队伍
     */
    @Override
    public FyTeam selectFyTeamByTeamId(Long teamId)
    {
    	
    	FyTeam fyTeam = fyTeamMapper.selectFyTeamByTeamId(teamId);
    	if(fyTeam==null) {
    		return null;
    	}
    	fyTeam.setFyUsers(fyUserMapper.selectFyUserListByTeamId(fyTeam.getTeamId()));
    	fyTeam.setFyPlace(fyPlaceMapper.selectFyPlaceByPlaceId(fyTeam.getPlaceId()));
        return fyTeam;
    }

    /**
     * 查询防疫队伍列表
     * 
     * @param fyTeam 防疫队伍
     * @return 防疫队伍
     */
    @Override
    public List<FyTeam> selectFyTeamList(FyTeam fyTeam)
    {
        return fyTeamMapper.selectFyTeamList(fyTeam);
    }

    /**
     * 新增防疫队伍
     * 
     * @param fyTeam 防疫队伍
     * @return 结果
     */
    @Override
    public int insertFyTeam(FyTeam fyTeam)
    {
        fyTeam.setCreateTime(DateUtils.getNowDate());
        return fyTeamMapper.insertFyTeam(fyTeam);
    }

    /**
     * 修改防疫队伍
     * 
     * @param fyTeam 防疫队伍
     * @return 结果
     */
    @Override
    public int updateFyTeam(FyTeam fyTeam)
    {
        fyTeam.setUpdateTime(DateUtils.getNowDate());
        return fyTeamMapper.updateFyTeam(fyTeam);
    }

    /**
     * 批量删除防疫队伍
     * 
     * @param teamIds 需要删除的防疫队伍主键
     * @return 结果
     */
    @Override
    public int deleteFyTeamByTeamIds(String teamIds)
    {
        return fyTeamMapper.deleteFyTeamByTeamIds(Convert.toStrArray(teamIds));
    }

    /**
     * 删除防疫队伍信息
     * 
     * @param teamId 防疫队伍主键
     * @return 结果
     */
    @Override
    public int deleteFyTeamByTeamId(Long teamId)
    {
        return fyTeamMapper.deleteFyTeamByTeamId(teamId);
    }
    

    /**
     * 通过队伍名称查询队伍
     * 
     * @param teamName 队伍名称
     * @return 防疫队伍对象信息
     */
    public FyTeam selectTeamByTeamName(String teamName) {
    	return fyTeamMapper.selectTeamByTeamName(teamName);
    }
    
    /**
     * 导入队伍数据
     * 
     * @param teamList 队伍数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importTeam(List<FyTeam> teamList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(teamList) || teamList.size() == 0)
        {
            throw new ServiceException("导入队伍数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        for (FyTeam team : teamList)
        {
            try
            {
                // 验证是否存在这个用户
                FyTeam u = fyTeamMapper.selectTeamByTeamName(team.getTeamName());
                FyPlace p = fyPlaceMapper.selectPlaceByPlaceName(team.getPlaceName());
                if(StringUtils.isNull(p)) {
                	failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、防疫队伍 " + team.getTeamName() + " 对应防疫点:"+team.getPlaceName()+"不存在");
                }else {
                	team.setPlaceId(p.getPlaceId());
	                if (StringUtils.isNull(u))
	                {
	                    BeanValidators.validateWithException(validator, team);
	                    team.setCreateBy(operName);
	                    team.setStatus(team.getStatus().equals("备用")?"2":"1");
	                    this.insertFyTeam(team);
	                    successNum++;
	                    successMsg.append("<br/>" + successNum + "、防疫队伍 " + team.getTeamName() + " 导入成功");
	                }
	                else if (isUpdateSupport)
	                {
	                    BeanValidators.validateWithException(validator, team);
	                    team.setTeamId(u.getTeamId());
	                    team.setUpdateBy(operName);
	                    this.updateFyTeam(team);
	                    successNum++;
	                    successMsg.append("<br/>" + successNum + "、防疫队伍 " + team.getTeamName() + " 更新成功");
	                }
	                else
	                {
	                    failureNum++;
	                    failureMsg.append("<br/>" + failureNum + "、防疫队伍 " + team.getTeamName() + " 已存在");
	                }
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、防疫队伍 " + team.getTeamName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 查场所管理树
     * @param fyTeam 场所信息
     * @return 所有场所信息
     */
    @Override
    public List<Ztree> selectTeamTree(FyTeam fyTeam,Long placeId,boolean checked)
    {
        List<FyTeam> teamList = fyTeamMapper.selectFyTeamListWithPlace(fyTeam);
        
        List<Ztree> ztrees = initZtree(teamList,placeId,checked);
        return ztrees;
    }
    
    /**
     * 对象转部门树
     *
     * @param teamList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FyTeam> teamList,Long placeId,boolean checked)
    {
    	List<Long> roleDeptList = new ArrayList<Long>();
    	if(checked) {
        	roleDeptList.add(placeId);
    	}
        return initZtree(teamList, roleDeptList);
    }

    /**
     * 对象转部门树
     *
     * @param teamList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FyTeam> teamList, List<Long> roleDeptList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (FyTeam fyTeam : teamList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(fyTeam.getTeamId());
            ztree.setpId(null);
            ztree.setName(fyTeam.getTeamName()+" "+(fyTeam.getPlaceName()==null?"":fyTeam.getPlaceName()+" "+fyTeam.getFyPlace().getAddr()));
            ztree.setTitle(fyTeam.getFyPlace().getAddr());
            if (isCheck)
            {
                ztree.setChecked(roleDeptList.contains(fyTeam.getPlaceId()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }
}
